package com.chinaunicom.service.impl;

import cn.hutool.core.util.IdUtil;
import com.chinaunicom.entity.ResponseResult;
import com.chinaunicom.service.IPayService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * @author: ruiyanglee
 * @date: 2020-11-06 23:19
 * @description:
 */
@Service
public class PayServiceImpl implements IPayService {
    @Value(value = "${server.port}")
    public String port;

    // 配置服务熔断策略
    @HystrixCommand(
            commandProperties = {
                    @HystrixProperty(name = "circuitBreaker.enabled", value = "true"), // 是否开启熔断
                    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), // 请求次数
                    @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "1000"), // 时间窗口
                    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60") // 失败率到达多少进行熔断跳闸
            })
    public ResponseResult getMsg() {
        return ResponseResult.ok().data("get msg from pay-service").flag(true).message("请求成功");
    }


    @HystrixCommand(
            commandProperties = {
                    @HystrixProperty(name = "circuitBreaker.enabled", value = "true"), // 是否开启熔断
                    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), // 请求次数
                    @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "1000"), // 时间窗口
                    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60") // 失败率到达多少进行熔断跳闸
            })
    public ResponseResult getPort() {
        return ResponseResult.ok().data("get server from " + port + " port").flag(true).message("请求成功");
    }

    @HystrixCommand(
            commandProperties = {
                    @HystrixProperty(name = "circuitBreaker.enabled", value = "true"), // 是否开启熔断
                    @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), // 请求次数
                    @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "1000"), // 时间窗口
                    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60") // 失败率到达多少进行熔断跳闸
            })
    public ResponseResult paymentCircuitBreaker(@PathVariable("id") Integer id) {
        if (id < 0) {
            throw new RuntimeException("******id 不能为负数");
        }
        String serialNumber = IdUtil.simpleUUID();  //UUID.randomUUID();
        return ResponseResult.ok().data(Thread.currentThread().getName() + "\t, port :" + port + "调用成功，流水号：" + serialNumber);
    }
}
